package org.itboys.mobile.service.mysql.web.pay;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.entity.mysql.pay.SundayPayConfig;
import org.itboys.mobile.entity.mysql.pay.SundayPayProduct;
import org.itboys.mongodb.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_支付_产品_service_web
 */
@Service
public class SundayPayProductService extends BaseMySqlService<SundayPayProduct>{
    @Autowired
    private SundayUploadService uploadFileService;
    /**
     * 查找支付配置
     * @param request
     * @return
     */
    public PageResult<SundayPayProduct> selectConfig(HttpServletRequest request){
        Map<String,Object> param= ParamUtil.packageMongoExactParam(request,"type");
        return new PageResult<SundayPayProduct>(super.select(param),super.count(param));

    }

    /**
     * 新增支付配置  如果有则修改
     * @param product
     */
    public void saveProduct(SundayPayProduct product, MultipartFile imageFile) throws  Exception{
        Map<String, String> map = uploadFileService.uploadSingle(imageFile);
        if(StringUtils.isNotEmpty(map.get(uploadFileService.UPLOAD_HALF_PATH))){

            product.setImage(map.get(uploadFileService.UPLOAD_HALF_PATH));
        }
        if(product.getId()==0l){
            //有且只能有一个
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("type",product.getType());
            if(LongUtil.isNotZreo(super.count(param))){
                throw new ErrorException("同类型支付产品，只能存在一个。");
            }
            super.insert(product);
        }else{
            //有且只能有一个
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("type",product.getType());
            param.put("id",product.getId());
            if(LongUtil.isNotZreo(super.count(param))){
                throw new ErrorException("同类型支付产品，只能存在一个。");
            }
            super.update(product);

        }
    }

    /**
     * 查找支付配置
     * @param id
     * @return
     */
    public SundayPayProduct findOne(Long id,Integer type){
        SundayPayProduct product = null;
        if(LongUtil.isNotZreo(id)){
            product=super.find(id);

        }else{
            product = new SundayPayProduct();
            product.setId(id);
            product.setType(type);
        }
        return product;
    }



}
